var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
const cors= require('cors');
var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// 跨域支持
app.use(cors())

//注册验证用户是否登录的中间件
const {
  expressjwt: expressJwt
} = require('express-jwt')

app.use(expressJwt({
  secret: 'kuaijian', //同加密的秘钥
  algorithms: ['HS256']
}).unless({
  //排除掉不需要做jwt验证的路由前缀
  // my前缀的路由中，查询评论列表是不需要做登录校验的
  path:[/^\/api\//,'/my/home/comments']
}))



// 全局中间件
app.use(function(req, res, next) {
   //封装返回数据的函数
   res.cc = function (status = 200, msg = '成功', data = []) {
     if (data.length > 0) {
       res.json({
         status,
         msg,
         data
       })
     } else {
       res.json({
         status,
         msg
       })
     }
   }
   next()
});

// 通过了验证
app.post('/my/home/checkLogin',(req,res)=>{
     // 获取到保存在token中的数据
     const username = req.auth.username
     return res.cc(200,'success',username)
})


// api路由
const catesRouter = require('./routes/cates')
const newsRouter = require('./routes/news')
const usersRouter = require('./routes/users')
const commentsRouter = require('./routes/comments')

app.use('/api',catesRouter)
app.use('/api',newsRouter)
app.use('/api',usersRouter)
app.use('/my', commentsRouter)


// 错误中间件
const joi = require('joi')
app.use(function(err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(400, err.message)
    // 返回jwt错误
     //如果是解析token的错误,提示解析错误相关
     if (err.name === 'UnauthorizedError') {
         return res.cc(401,err.message)
     }
    // 未知错误
    res.cc(500, err.message)
});

module.exports = app;
